<template>
  <div class="hello">
    <div class="canvas" ref="threejsContainer"></div>

    <!-- 加载模型的按钮 -->
    <button @click="loadModel">加载模型</button>
    <!-- 控制模型的按钮 -->
    <button @click="increaseScale">增大尺寸</button>
    <button @click="decreaseScale">减小尺寸</button>
    <button @click="moveUp">上移</button>
    <button @click="moveDown">下移</button>
  </div>
</template>

<script>
import * as THREE from 'three';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader';

//可以使用Three.js的 OrbitControls 控件来允许用户自由地旋转和缩放场景，从而更容易地从不同角度观察模型。
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';

// 确保这里的路径与您放置模型的实际路径相匹配
import demoModel from '@/assets/models/demo.gltf';

export default {
  name: 'ThreeJsComponent',
  data() {
    return {
      scene: null, // 创建场景
      model: null, // 添加一个属性来保存模型的引用
      cylinderModel: null,
      cubeModel: null,
    };
  },
  props: {
    msg: String
  },
  mounted() {
    this.initThreeJS();
  },
  methods: {
    initThreeJS() {
      let container = this.$refs.threejsContainer;

      // 创建场景
      const scene = new THREE.Scene();
      this.scene = scene;

      // 创建相机
      const camera = new THREE.PerspectiveCamera(75, container.offsetWidth / container.offsetHeight, 0.1, 1000);
      // 设置相机的位置
      camera.position.set(0, 800, 0);  //camera.position.set(x, y, z);  //camera.position.z = 5; 单独控制z轴

      // 设置相机朝向场景的中心点（或者任何感兴趣的点）
      camera.lookAt(scene.position);

      // 添加辅助工具
      /* const axesHelper = new THREE.AxesHelper(5);
      scene.add(axesHelper);

      const gridHelper = new THREE.GridHelper(10, 10);
      scene.add(gridHelper); */

      // 创建渲染器
      const renderer = new THREE.WebGLRenderer();
      renderer.setSize(container.offsetWidth, container.offsetHeight);
      container.appendChild(renderer.domElement);

      // 添加OrbitControls
      const controls = new OrbitControls(camera, renderer.domElement);
      controls.target.set(0, 0, 0); // 控制器目标点（场景中心）

      // 添加环境光
      const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
      scene.add(ambientLight);

      // 添加方向光
      const directionalLight = new THREE.DirectionalLight(0xffffff, 0.5);
      directionalLight.position.set(1, 1, 0); // 可根据实际情况调整位置
      scene.add(directionalLight);

      // 加载GLTF模型
      /* const loader = new GLTFLoader();
      loader.load(demoModel, (gltf) => {
        gltf.scene.traverse((child) => {
          if (child.isMesh) {
            // 为模型的每个部分应用一个基础材质
            child.material = new THREE.MeshStandardMaterial({ color: 0x00ff30 });
          }
        });
        scene.add(gltf.scene);
        this.model = gltf.scene; // 保存模型引用
      }, undefined, function (error) {
        console.error(error);
      }); */

      // 动画循环
      function animate() {
        requestAnimationFrame(animate);
        controls.update(); // 更新控制器 只有在使用阻尼或自动旋转时才需要
        renderer.render(scene, camera);
      }
      animate();
    },

    loadModel() {
      // 检查模型是否已经被加载
      if (this.cylinderModel || this.cubeModel) {
        console.log("模型已经加载");
        return;
      }


      const loader = new GLTFLoader();
      const crystalMaterial = this.createCrystalMaterial(); // 创建水晶材质

      loader.load(demoModel, (gltf) => {
        let cylinderModel = null; // 圆柱体模型
        let cubeModel = null;     // 立方体模型
        gltf.scene.traverse((child) => {
          if (child.isMesh) {
            //child.material = new THREE.MeshStandardMaterial({ color: 0x00ff30 });
            child.material = crystalMaterial; // 应用水晶材质

            // 根据名称区分模型
            if (child.name === '圆柱体') {
              cylinderModel = child;
              child.material = new THREE.MeshStandardMaterial({ color: 0xff0080 }); // 应用红色材质
            } else if (child.name === '立方体') {
              cubeModel = child;
              child.material = new THREE.MeshStandardMaterial({ color: 0x4f87ff }); // 蓝色材质
            }
          }
        });
        /* this.scene.add(gltf.scene); // 确保使用 this.scene
        this.model = gltf.scene; // 保存模型引用 */

        if (cylinderModel && cubeModel) {
          this.scene.add(cylinderModel);
          this.scene.add(cubeModel);
          this.cylinderModel = cylinderModel; // 保存圆柱体模型引用
          this.cubeModel = cubeModel;         // 保存立方体模型引用
        }
      }, undefined, function (error) {
        console.error(error);
      });
    },
    //增大尺寸
    increaseScale() {
      if (this.cylinderModel) {
        this.cylinderModel.scale.x *= 1.1;
        this.cylinderModel.scale.y *= 1.1;
        this.cylinderModel.scale.z *= 1.1;
      }
    },
    //减小尺寸
    decreaseScale() {
      if (this.cylinderModel) {
        this.cylinderModel.scale.x /= 1.1;
        this.cylinderModel.scale.y /= 1.1;
        this.cylinderModel.scale.z /= 1.1;
      }
    },
    //上移
    moveUp() {
      if (this.cylinderModel) {
        this.cylinderModel.position.y += 2;
      }
    },
    //下移
    moveDown() {
      if (this.cylinderModel) {
        this.cylinderModel.position.y -= 2;
      }
    },
    //透明材质
    createCrystalMaterial() {
      return new THREE.MeshPhysicalMaterial({
        color: 0x00ff30,
        transparency: 0.9,
        transparent: true,
        roughness: 0,
        metalness: 0,
        reflectivity: 0.5,
        clearcoat: 0.5,
        clearcoatRoughness: 0
      });
    },
  }
}
</script>

<style lang='scss' scoped>
h3 {
  margin: 40px 0 0;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #4f87ff;
}
.hello{
  width: 1000px;
  height: 800px;
}
.canvas{
  width: 100%;
  height: 100%;
}
</style>
